package com.woniuxy.userapp.app.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.nimbusds.jose.JWSObject;
import com.woniuxy.commons.util.Result;
import com.woniuxy.commons.util.UserDto;
import com.woniuxy.commons.util.WebUtil;
import com.woniuxy.userapp.client.VenueClient;
import com.woniuxy.userapp.client.param.AddVenueInfo;
import com.woniuxy.userapp.client.param.VenueInfo;
import com.woniuxy.userapp.client.param.VenueOpenOrCloseInfo;
import com.woniuxy.userapp.common.exception.Myexception.UserException;
import com.woniuxy.userapp.common.exception.code.UserExceptionCode;
import com.woniuxy.userapp.common.util.TokenToUserDtoUtil;
import com.woniuxy.userapp.infra.model.mapper.model.FrontAccount;
import com.woniuxy.userapp.infra.model.mapper.model.Venue;
import com.woniuxy.userapp.service.FrontAccountService;
import com.woniuxy.userapp.service.VenueService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.time.LocalDate;


/**
 * <p>
 *  场馆
 * </p>
 *
 * @author 
 * @since 2022-08-03
 */
@RestController
public class VenueController implements VenueClient {

    @Autowired
    private VenueService venueService;
    @Autowired
    private VenueClient venueClient;
    @Autowired
    private FrontAccountService frontAccountService;

    BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /**
     * 修改场馆的状态:开业歇业
     */
    public Result venueOpenOrClose(VenueOpenOrCloseInfo venueOpenOrCloseInfo){
        System.out.println("1111111111");
        if( venueOpenOrCloseInfo.getOpenOrCloseCode()!= 1 && venueOpenOrCloseInfo.getOpenOrCloseCode() != 0 && venueOpenOrCloseInfo.getOpenOrCloseCode() != 2) throw new UserException(UserExceptionCode.VENUE_state_ERROR);
        //判断场馆是否存在
        Venue venue = venueService.getOne(new QueryWrapper<Venue>().eq("id", venueOpenOrCloseInfo.getVenueId()));
        if(venue == null) throw new UserException(UserExceptionCode.VENUE_NOT_EXISTS);
        venueService.update(null,new UpdateWrapper<Venue>().set("open_or_close",venueOpenOrCloseInfo.getOpenOrCloseCode()).eq("id",venueOpenOrCloseInfo.getVenueId()));
        System.out.println("2222222222222222222");
        return Result.getInstance().setMsg("修改场馆状态成功").setCode(200);
    }

    /**
     * 根据前台账户id查询Alipay账户
     */
    public Result<VenueInfo> loadAlipayById(Integer account_id){
        Venue venue = venueService.getOne(new QueryWrapper<Venue>().eq("front_account_id", account_id));
        if(venue == null) throw new UserException(UserExceptionCode.VENUE_NOT_EXISTS);
        VenueInfo venueInfo = BeanUtil.copyProperties(venue, VenueInfo.class);
        return Result.getInstance(VenueInfo.class).setCode(200).setMsg("查询成功").setData(venueInfo);
    }


    public Result<Integer> findAccountIdByVenueId(Integer VenueId) {

//        String user = WebUtil.getRequest().getHeader("user");
//        System.out.println(user);
//        String token="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJMb2dpbk5hbWUiOiJzdHVkZW50IiwiTG9naW5JZCI6MywidXNlcl9uYW1lIjoic3R1ZGVudCIsInNjb3BlIjpbImFsbCJdLCJMb2dpblJvbGUiOlsiMyJdLCJleHAiOjE2NjAzMDQ4MDAsImF1dGhvcml0aWVzIjpbIjNfc3R1ZGVudCJdLCJqdGkiOiI3ZTEwODk0Ny1mN2UxLTRiOGUtYTQ3Mi1iMjg1NWVlOTU0NmIiLCJjbGllbnRfaWQiOiJwb3J0YWwtYXBwIn0.RIsg-2jSxsp4LWq8KF0xeJRuFqtS_LfLVqNU2DnuiOsjIVexNptmcfpIn-quZs_y95SpjeF-9LQeZBJMmR4VxvoH3Lb8AJqbUMo_KNUP1uaUhiDUVyDa3EZXoo-gffbXuKNTqAHqt477049M8byr0UT6jYtgfJqcUwzYtFsxVpfantIkUshOjtv2yrfaXUo0EjPvLgrUKWsx30Ouuqh8KTOMALjBc_JzORsd3M-LyeT8pEEgUKOSku66QRAT4NmrfPwokdGSokY6RNwfqxifdvOr8nUOCypUzlMOaVtmgsqiQFQp_I9MapAX8RoAC_NvmYFZ_WupV24TWgTu64H0Jw";
//        String realtoken = token.replace("Bearer ", "");
//        JWSObject jwsObject = null;
//        try {
//            jwsObject = JWSObject.parse(realtoken);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        String userStr = jwsObject.getPayload().toString();
//        System.out.println(userStr.toString());


        Venue venue = venueService.getOne(new QueryWrapper<Venue>().eq("id", VenueId));
        if(venue == null) throw new UserException(UserExceptionCode.VENUE_NOT_EXISTS);
        return Result.getInstance(Integer.class).setData(venue.getFrontAccountId()).setCode(200);
    }

    @Override
    public Result<VenueInfo> findVenueByAccountId(Integer account_id) {
        Venue venue = venueService.getOne(new QueryWrapper<Venue>().eq("front_account_id", account_id));
        if(venue == null) throw new UserException(UserExceptionCode.VENUE_NOT_EXISTS);
        VenueInfo venueInfo = BeanUtil.copyProperties(venue, VenueInfo.class);
        return Result.getInstance(VenueInfo.class).setCode(200).setMsg("查询成功").setData(venueInfo);
    }

    @Override
    public Result<VenueInfo> findVenueByVenueId(Integer venueId) {
        Venue venue = venueService.getOne(new QueryWrapper<Venue>().eq("id", venueId));
        if(venue == null) throw new UserException(UserExceptionCode.VENUE_NOT_EXISTS);
        VenueInfo venueInfo = BeanUtil.copyProperties(venue, VenueInfo.class);
        return Result.getInstance(VenueInfo.class).setData(venueInfo).setCode(200);
    }

    /**
     * 完善场馆信息
     * @param addvenueInfo
     * @return
     */

    @Override
    public Result addVenue(AddVenueInfo addvenueInfo) {
        String header = WebUtil.getRequest().getHeader("user");
        JSONObject entries = new JSONObject(header);
        Integer account_id = Integer.valueOf(entries.getStr("LoginId"));
        Result<VenueInfo> Venueresult = venueClient.findVenueByAccountId(account_id);
        //不应该会抛出此异常,因为是根据token中的数据查出accountid,且该路径权限属于场馆,其他token
        //也无法通过鉴权
        if(Venueresult.getData() == null) throw new UserException(UserExceptionCode.VENUE_NOT_EXISTS);

        //先在账户表中查询是否有此qq.email,phone,再更新账户表中的数据,最后跟心教练表
        //判断电话是否重复
        String phone = addvenueInfo.getPhone();
        FrontAccount frontAccount = frontAccountService.getOne(new QueryWrapper<FrontAccount>().eq("phone", phone));
        if(frontAccount != null){
            if(frontAccount.getId() != account_id)throw new UserException(UserExceptionCode.PHONE_IS_EXISTS);
        }
//        if(frontAccount != null)throw new UserException(UserExceptionCode.PHONE_IS_EXISTS);

        //账户表更新
        FrontAccount updateFrontAccount = new FrontAccount();
        updateFrontAccount.setId(account_id);
        updateFrontAccount.setPhone(phone);
        updateFrontAccount.setWalletPwd(encoder.encode(addvenueInfo.getWalletPwd()));
        frontAccountService.saveOrUpdate(updateFrontAccount,new QueryWrapper<FrontAccount>().eq("id",account_id));


        //前台账户id(根据当前登录用户获取前台账户id,然后更新)
        addvenueInfo.setFrontAccountId(account_id);
        Venue venue = BeanUtil.copyProperties(addvenueInfo, Venue.class);
        boolean save = venueService.saveOrUpdate(venue, new UpdateWrapper<Venue>().eq("front_account_id", account_id));
        if(!save) throw new UserException(UserExceptionCode.VENUE_ADD_FAILS);
        return Result.getInstance().setCode(200).setMsg("新增场馆信息成功");
    }
}

